package com.threegroup.admin.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.threegroup.admin.dao.SysRoleUserDao;
import com.threegroup.admin.entity.SysRoleUserEntity;
import com.threegroup.admin.security.user.SecurityUser;
import com.threegroup.admin.service.ISysRoleUserService;

import com.threegroup.common.utils.AssertUtil;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 角色用户关系
 *
 */
@Service
public class SysRoleUserServiceImpl implements ISysRoleUserService {

    @Resource
    private SysRoleUserDao sysRoleUserDao;

    @Override
    public void saveOrUpdate(Long userId, List<Long> roleIdList) {

        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        //先删除角色用户关系
        deleteByUserIds(new Long[]{userId});

        //用户没有一个角色权限的情况
        if(CollUtil.isEmpty(roleIdList)){
            return ;
        }

        //保存角色用户关系
        for(Long roleId : roleIdList){
            SysRoleUserEntity sysRoleUserEntity = new SysRoleUserEntity();
            sysRoleUserEntity.setUserId(userId);
            sysRoleUserEntity.setRoleId(roleId);
            sysRoleUserEntity.setCreator(securityUser.getUid());
            sysRoleUserEntity.setCreateDate(new Date());

            //保存
            AssertUtil.isTrue(sysRoleUserDao.save(sysRoleUserEntity) < 1, "保存失败");
        }
    }

    @Override
    public void deleteByRoleIds(Long[] roleIds) {
        sysRoleUserDao.deleteByRoleIds(roleIds);
    }

    @Override
    public void deleteByUserIds(Long[] userIds) {
        sysRoleUserDao.deleteByUserIds(userIds);
    }

    @Override
    public List<Long> getRoleIdList(Long userId) {

        return sysRoleUserDao.getRoleIdList(userId);
    }
}